package com.wuchengdong.web.extend.utils;

import java.security.SecureRandom;
import java.util.Random;

/**
 * 随机生成验证码工具类
 */
public class ValidateCodeOrTokenUtils {
    /**
     * 随机生成4-6位数字验证码
     * @param length 长度为4位或者6位
     * @return
     */
    public static Integer generateValidateCode(int length){
        Integer code =null;
        if(length == 4){
            code = new Random().nextInt(9999);//生成随机数，最大为9999
            if(code < 1000){
                code = code + 1000;//保证随机数为4位数字
            }
        }else if(length == 6){
            code = new Random().nextInt(999999);//生成随机数，最大为999999
            if(code < 100000){
                code = code + 100000;//保证随机数为6位数字
            }
        }else{
            throw new RuntimeException("只能生成4位或6位数字验证码");
        }
        return code;
    }

    /**
     * 随机生成指定长度字符串
     * @param length 长度
     * @return
     */
    private static final String CHARACTERS = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789";
    public static String generateToken(int length) {
        // 使用当前时间戳作为种子
        long timestamp = System.currentTimeMillis();
        SecureRandom random = new SecureRandom(Long.toString(timestamp).getBytes());

        StringBuilder token = new StringBuilder(length);
        for (int i = 0; i < length; i++) {
            token.append(CHARACTERS.charAt(random.nextInt(CHARACTERS.length())));
        }
        return token.toString();
    }

}
